package com.longlong.service.impl;


import com.longlong.config.globalExceptionClass.BusinessException;
import com.longlong.config.security.service.UserDetailsServiceImpl;
import com.longlong.entity.AdminUser;
import com.longlong.mapper.AdminUserMapper;
import com.longlong.service.AdminUserService;
import com.longlong.utils.SecurityUtil;
import com.longlong.utils.TokenUtil;
import com.longlong.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class AdminUserServiceImpl implements AdminUserService {

    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private TokenUtil tokenUtil;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Value("${jwt.tokenHead}")
    private String tokenHead;
    /*
    * 登录接口
    * @Param LoginVo 登录参数:账号密码
    * @Return 返回token,用token去获取资源
    * */
    @Override
    public Object login(LoginVo loginVo){
        log.info("开始登陆");
        UserDetails userDetails = userDetailsService.loadUserByUsername(loginVo.getUsername());
        if(userDetails == null || !passwordEncoder.matches(loginVo.getPassword(),userDetails.getPassword())){
            throw new BusinessException(402 ,"用户名和密码有误!!!");
        }
        log.info("登录成功，在security对象中存入登陆信息");
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        log.info("根据登录信息，获取token");
        //需要jwt来生成token
        String token= tokenUtil.generateToken(userDetails);
        Map<String, String> map = new HashMap<>();
        log.info(tokenHead);
        map.put("tokenHead",tokenHead);
        map.put("token",token);
        return map;
    }
    @Override
    public AdminUser findAdminUserInfoById() {
        AdminUser adminUserInfo = adminUserMapper.findAdminUserInfo(SecurityUtil.getUserId());

        adminUserInfo.setPassword("别闹");

        return adminUserInfo;
    }
}
























